<template>
    <div class="search-suggestion">
        <van-cell
            icon="search"
            v-for="item in suggestion"
            :key="item.videoId"
        >
            <div
                slot="title"
                v-html="hightlight(item.title)"
                @click="clickSuggestion(item)"
            ></div>
        </van-cell>
    </div>
</template>

<script>
import { debounce } from 'lodash'
export default {
    name: 'SearchSuggestion',
    props: {
        searchText: {
            type: String,
            required: true
        },
        recommendList: {
            type: Array,
            required: true
        }
    },
    data() {
        return {
            suggestion: []
        };
    },
    watch: {
        // 监听输入框文字变化  实现搜索时的联想建议
        searchText: {
            immediate: true,
            // handler: debounce(function(val) {
            //     this.loadSearchSuggestion(val);
            // }, 500)
            handler: debounce(function search(val) {
                // 这里对拉取到的所有数据进行筛选 返回联想建议的数组
                this.suggestion = this.recommendList.filter(item => item.title.includes(val));
            }, 300)
        }
    },
    methods: {
        // 匹配的文字高亮显示
        hightlight(str) {
            const hightlightStr = `<span class="active">${this.searchText}</span>`;
            const regExp = new RegExp(this.searchText.trim(), 'ig');
            return str.replace(regExp, hightlightStr);
        },
        // 点击联想建议项时
        clickSuggestion(item) {
            this.$emit('search', item.title)
            // this.$router.push(`/episode/${item.videoId}`)
        }
    }
};
</script>

<style scoped lang="scss">
.search-suggestion {
    text-align: left;
    /deep/ .active {
        color: red;
    }
    /deep/ .van-cell {
        padding: 0 40px;
        height: 90px;
        font-size: 34px;
        line-height: 90px;
        .van-icon {
            font-size: 30px;
            line-height: 90px;
        }
    }
}
</style>
